package org.example.ims.Service.Base.Impl;

import org.example.ims.Service.Base.SalesmanService;
import org.example.ims.Entity.Base.Salesman;
import org.example.ims.Repository.Base.SalesmanRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service("salesmanService")
public class SalesmanServiceImpl implements SalesmanService {

    private final SalesmanRepository salesmanRepository;

    @Autowired
    public SalesmanServiceImpl(SalesmanRepository salesmanRepository) {
        this.salesmanRepository = salesmanRepository;
    }

    @Override
    // 创建销售员
    public Salesman createSalesman(Salesman salesman) {
        return salesmanRepository.save(salesman);
    }

    @Override
    public Page<Salesman> getAllSalesmen(Integer page, Integer size) {
        return salesmanRepository.findAll(PageRequest.of(page, size));
    }

    @Override
    public Page<Salesman> searchSalesmen(String name, String department, Integer page, Integer size) {
        return salesmanRepository.searchSalesmen(
                name, department, PageRequest.of(page, size)
        );
    }

    @Override
    // 根据ID获取销售员
    public Optional<Salesman> getSalesmanById(Integer id) {
        return salesmanRepository.findById(id);
    }

    @Override
    public Salesman getSalesmanByName(String name) {
        return salesmanRepository.findBySalesmanName(name);
    }

    @Override
    // 更新销售员信息
    public Salesman updateSalesman(Integer id, Salesman salesmanDetails) {
        Optional<Salesman> salesman = salesmanRepository.findById(id);
        if (salesman.isPresent()) {
            Salesman _salesman = salesman.get();
            _salesman.setSalesmanName(salesmanDetails.getSalesmanName());
            _salesman.setDepartment(salesmanDetails.getDepartment());
            return salesmanRepository.save(_salesman);
        }
        return null;
    }

    @Override
    // 删除销售员
    public void deleteSalesman(Integer id) {
        if (!salesmanRepository.existsById(id)) {
            throw new RuntimeException("Salesman does not exist");
        }
        salesmanRepository.deleteById(id);
    }
}